import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';

/// 日期筛选弹窗
/// [context] 上下文
/// [start] 初始开始时间
/// [end] 初始结束时间
/// 返回选中的[start, end]，未选择返回null
Future<List<DateTime>?> showDateFilterDialog({
  required BuildContext context,
  DateTime? start,
  DateTime? end,
}) async {
  return await showDialog<List<DateTime>>(
    context: context,
    barrierDismissible: false,
    useSafeArea: false,
    builder:
        (context) => DateFilterDialog(
          start: start ?? DateTime.now(),
          end: end ?? DateTime.now(),
        ),
  );
}

class DateFilterDialog extends StatefulWidget {
  final DateTime start;
  final DateTime end;
  const DateFilterDialog({super.key, required this.start, required this.end});

  @override
  State<DateFilterDialog> createState() => _DateFilterDialogState();
}

class _DateFilterDialogState extends State<DateFilterDialog> {
  late DateTime _startDate;
  late DateTime _endDate;
  int _selectedTab = 0; // 0: 开始时间, 1: 结束时间
  late String _startString = '开始时间';
  late String _endString = '结束时间';

  @override
  void initState() {
    super.initState();
    _startDate = widget.start;
    _endDate = widget.end;
  }

  // Widget _buildPicker(DateTime date, ValueChanged<DateTime> onChanged) {
  //   return SizedBox(
  //     height: 180,
  //     child: Row(
  //       children: [
  //         Expanded(
  //           child: CupertinoPicker(
  //             scrollController: FixedExtentScrollController(
  //               initialItem: _startDate.year - 2020,
  //             ),
  //             itemExtent: 36,
  //             onSelectedItemChanged: (i) {
  //               onChanged(DateTime(2020 + i, date.month, date.day));
  //             },
  //             children: List.generate(
  //               10,
  //               (i) => Center(
  //                 child: Text(
  //                   '${2020 + i}年',
  //                   style: const TextStyle(fontSize: 18.px),
  //                 ),
  //               ),
  //             ),
  //           ),
  //         ),
  //         Expanded(
  //           child: CupertinoPicker(
  //             scrollController: FixedExtentScrollController(
  //               initialItem: _startDate.month - 1,
  //             ),
  //             itemExtent: 36,
  //             onSelectedItemChanged: (i) {
  //               onChanged(DateTime(date.year, i + 1, date.day));
  //             },
  //             children: List.generate(
  //               12,
  //               (i) => Center(
  //                 child: Text(
  //                   '${i + 1}月',
  //                   style: const TextStyle(fontSize: 18.px),
  //                 ),
  //               ),
  //             ),
  //           ),
  //         ),
  //         Expanded(
  //           child: CupertinoPicker(
  //             scrollController: FixedExtentScrollController(
  //               initialItem: _startDate.day - 1,
  //             ),
  //             itemExtent: 36,
  //             onSelectedItemChanged: (i) {
  //               onChanged(DateTime(date.year, date.month, i + 1));
  //             },
  //             children: List.generate(
  //               31,
  //               (i) => Center(
  //                 child: Text(
  //                   '${i + 1}日',
  //                   style: const TextStyle(fontSize: 18.px),
  //                 ),
  //               ),
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  Widget _buildPicker(DateTime date, ValueChanged<DateTime> onChanged) {
    // 确保日期有效，避免无效日期导致的错误
    DateTime validDate = date;
    try {
      // 验证日期是否有效，如果无效则使用当前日期
      validDate = DateTime(date.year, date.month, date.day);
    } catch (e) {
      validDate = DateTime.now();
    }

    return SizedBox(
      height: 180,
      child: Row(
        children: [
          Expanded(
            child: CupertinoPicker(
              scrollController: FixedExtentScrollController(
                initialItem: validDate.year - 2020,
              ),
              itemExtent: 36,
              onSelectedItemChanged: (i) {
                final newYear = 2020 + i;
                // 确保新日期有效
                try {
                  final newDate = DateTime(
                    newYear,
                    validDate.month,
                    validDate.day,
                  );
                  onChanged(newDate);
                } catch (e) {
                  // 如果日期无效，使用该月的最后一天
                  final lastDay = DateTime(newYear, validDate.month + 1, 0).day;
                  onChanged(DateTime(newYear, validDate.month, lastDay));
                }
              },
              children: List.generate(
                20,
                (i) => Center(
                  child: Text(
                    '${2020 + i}年',
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: CupertinoPicker(
              scrollController: FixedExtentScrollController(
                initialItem: validDate.month - 1,
              ),
              itemExtent: 36,
              onSelectedItemChanged: (i) {
                final newMonth = i + 1;
                // 确保新日期有效
                try {
                  final newDate = DateTime(
                    validDate.year,
                    newMonth,
                    validDate.day,
                  );
                  onChanged(newDate);
                } catch (e) {
                  // 如果日期无效，使用该月的最后一天
                  final lastDay = DateTime(validDate.year, newMonth + 1, 0).day;
                  onChanged(DateTime(validDate.year, newMonth, lastDay));
                }
              },
              children: List.generate(
                12,
                (i) => Center(
                  child: Text(
                    '${i < 9 ? '0' : ''}${i + 1}月',
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: CupertinoPicker(
              scrollController: FixedExtentScrollController(
                initialItem: validDate.day - 1,
              ),
              itemExtent: 36,
              onSelectedItemChanged: (i) {
                final newDay = i + 1;
                // 确保新日期有效
                try {
                  final newDate = DateTime(
                    validDate.year,
                    validDate.month,
                    newDay,
                  );
                  onChanged(newDate);
                } catch (e) {
                  // 如果日期无效，使用该月的最后一天
                  final lastDay =
                      DateTime(validDate.year, validDate.month + 1, 0).day;
                  onChanged(DateTime(validDate.year, validDate.month, lastDay));
                }
              },
              children: List.generate(
                31,
                (i) => Center(
                  child: Text(
                    '${i < 9 ? '0' : ''}${i + 1}日',
                    style: const TextStyle(fontSize: 18),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTabButton(String text, int index) {
    final bool selected = _selectedTab == index;
    return Expanded(
      child: GestureDetector(
        onTap: () => setState(() => _selectedTab = index),
        child: Container(
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color:
                    selected
                        ? AppColors.fontColorSearch
                        : AppColors.fontColorGrey,
              ),
            ),
          ),
          child: Center(
            child: Text(
              text,
              style: TextStyle(
                color:
                    selected
                        ? AppColors.fontColorSearch
                        : AppColors.fontColorGrey,
                fontSize: 18.px,
                fontWeight: selected ? FontWeight.bold : FontWeight.normal,
              ),
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final double bottom = MediaQuery.of(context).viewInsets.bottom;
    return Material(
      color: Colors.black.withOpacity(0.3),
      child: Stack(
        children: [
          // GestureDetector(
          //   onTap: () => Navigator.of(context).pop(),
          //   child: Container(color: Colors.transparent),
          // ),
          Align(
            alignment: Alignment.bottomCenter,
            child: ClipRRect(
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(32),
              ),
              child: Container(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.only(
                  left: 0,
                  right: 0,
                  top: 20.px,
                  bottom: bottom > 0 ? bottom : 32,
                ),
                child: Stack(
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text(
                          '交易时间',
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 16.px),

                        Row(
                          children: [
                            const SizedBox(width: 24),
                            _buildTabButton(_startString, 0),
                            SizedBox(
                              width: 32.px,
                              child: Center(
                                child: Text(
                                  '至',
                                  style: TextStyle(
                                    color: AppColors.fontColorGrey,
                                    fontSize: 18.px,
                                  ),
                                ),
                              ),
                            ),
                            _buildTabButton(_endString, 1),
                            const SizedBox(width: 24),
                          ],
                        ),
                        SizedBox(height: 10.px),

                        Center(
                          child: Text(
                            '最多可查找时间跨度一年的交易',
                            style: TextStyle(
                              fontSize: 14.px,
                              color: AppColors.fontColorgrey3600,
                            ),
                          ),
                        ),
                        SizedBox(height: 10.px),
                        // 使用key强制重建时间选择器，确保切换标签时正确更新
                        KeyedSubtree(
                          key: ValueKey(_selectedTab),
                          child: _buildPicker(
                            _selectedTab == 0 ? _startDate : _endDate,
                            (d) {
                              setState(() {
                                if (_selectedTab == 0) {
                                  _startDate = d;
                                  _startString =
                                      '${_startDate.year}年${_startDate.month}月${_startDate.day}日';
                                } else {
                                  _endDate = d;
                                  _endString =
                                      '${_endDate.year}年${_endDate.month}月${_endDate.day}日';
                                }
                              });
                            },
                          ),
                        ),
                        const SizedBox(height: 32),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ButtonWidget(
                              label: '取消',
                              height: 36.px,
                              width: 125.px,
                              fontSize: 14.px,
                              fontColor: AppColors.fontColor21,
                              onPressed: () => Navigator.of(context).pop(),
                            ),
                            const SizedBox(width: 38),
                            ButtonWidget(
                              label: '完成',
                              height: 36.px,
                              width: 125.px,
                              fontSize: 14.px,
                              fontColor: AppColors.fontColor21,
                              onPressed:
                                  () => Navigator.of(
                                    context,
                                  ).pop([_startDate, _endDate]),
                            ),
                            const SizedBox(width: 16),
                          ],
                        ),
                        const SizedBox(height: 16),
                      ],
                    ),
                    // 右上角关闭按钮
                    // Positioned(
                    //   right: 16,
                    //   top: 0,
                    //   child: GestureDetector(
                    //     onTap: () => Navigator.of(context).pop(),
                    //     child: Container(
                    //       width: 40,
                    //       height: 40,
                    //       decoration: BoxDecoration(
                    //         color: Colors.white,
                    //         shape: BoxShape.circle,
                    //         boxShadow: [
                    //           BoxShadow(
                    //             color: Colors.black.withOpacity(0.08),
                    //             blurRadius: 8,
                    //           ),
                    //         ],
                    //       ),
                    //       child: ImageAssetWidget(
                    //         imageUrl: 'static/images/close_ico.png',
                    //         width: 24,
                    //         height: 24,
                    //       ),
                    //     ),
                    //   ),
                    // ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
